package com.ly.controller;

import com.ly.common.Result;
import com.ly.common.StatusEnum;
import com.ly.common.TokenHandler;
import com.ly.dao.UserDao;
import com.ly.dao.UserTokenDao;
import com.ly.entity.User;
import com.ly.rep.LoginRep;
import com.ly.req.LoginReq;
import com.ly.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/web")
@Api(tags = "web模块")
public class WebController {
    @Resource
    public UserService userService;
    @Resource
    public UserTokenDao userTokenDao;
    @Resource
    public UserDao userDao;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result<?> register(@RequestBody @Validated User user){
        Boolean register = userService.register(user);
        if(register){
            return  new Result<>(StatusEnum.SUCCESS);
        }
        return new Result<>(StatusEnum.ERROR,"注册失败");
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<?> login(@RequestBody @Validated LoginReq loginReq){
        LoginRep loginRep = userService.login(loginReq);
        return  new Result<>(loginRep,StatusEnum.SUCCESS);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result<?> logout(HttpServletRequest httpServletRequest){
        User userInfo = TokenHandler.getUserInfo();
        //删除用户token
        userTokenDao.deleteByToken(httpServletRequest.getHeader("token"));
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @GetMapping("/getPersonInfo")
    @ApiOperation(value = "个人信息")
    public Result<?> getPersonInfo(){
        User userInfo = TokenHandler.getUserInfo();
        return  new Result<>(userInfo,StatusEnum.SUCCESS);
    }

    @PostMapping("/updatePersonInfo")
    @ApiOperation(value = "修改个人信息")
    public Result<?> updatePersonInfo(@RequestBody User user){
        userDao.updateById(user);
        return  new Result<>(StatusEnum.SUCCESS);
    }
}
